<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<canvas width="512" height="480" id="mycan">

</canvas>
</body>
</html>
<script>
    var mycan=document.getElementById("mycan");
    var can=mycan.getContext("2d");
    hero={};
    hero.move= function () {
        hero.x+=hero.vx;
        hero.x=hero.x<30?30:hero.x;
        hero.x=hero.x>mycan.clientWidth-60?mycan.clientWidth-60:hero.x;
        hero.y+=hero.vy;
        hero.y=hero.y<0?0:hero.y;
        hero.y=hero.y>mycan.clientHeight-62?mycan.clientHeight-62:hero.y;
    }
    monster={};
    var loadhero=false;
    var loadmonster=false;
    var loadbg=false;
    var count=0;
    var heroimg=new Image();
    heroimg.onload= function () {
        loadhero=true;
        hero.x=mycan.clientWidth*0.5-this.width*0.5
        hero.y=mycan.clientHeight*0.5-this.height*0.5;
        hero.vx=0;
        hero.vy=0;
    }
    heroimg.src="images/hero.png";
    var monsterimg=new Image();
    monsterimg.onload= function () {
        loadmonster=true;
    }
    monsterimg.src="images/monster.png";
    var bg=new Image();
    bg.onload= function () {
        loadbg=true;
    }
    bg.src="images/background.png";

    function init(){
        monster.x=Math.random()*(mycan.clientWidth-30-60)+30;
        monster.y=Math.random()*(mycan.clientHeight-30-62)+30;
    }

    function  catchMonster(){
        if(Math.abs(hero.x-monster.x)<30&&Math.abs(hero.y-monster.y)<32){
            init();
            ++count;
        }
    }

    function render(){
        if(loadbg){
            can.drawImage(bg,0,0);
        }
        if(loadhero){
            can.drawImage(heroimg,hero.x,hero.y);
        }
        if(loadmonster){
            can.drawImage(monsterimg,monster.x,monster.y);
        }
        can.font="20px 楷体";
        can.fillStyle="white";
        can.fillText("抓怪数:"+count,20,30);
        hero.move();
        catchMonster();
    }

    window.addEventListener("keydown", function (e) {
        if(e.keyCode==37){
            hero.vx=-2;
        }else if(e.keyCode==40){
            hero.vy=2;
        }else if(e.keyCode==39){
            hero.vx=2;
        }else if(e.keyCode==38){
            hero.vy=-2;
        }
    })

    window.addEventListener("keyup", function (e) {
        hero.vx=0;
        hero.vy=0;
    })

    init();

    window.setInterval("render()",20);
</script>
